from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.http import Http404

class KeywordDB(models.Model):
	keyword = models.CharField(max_length = 200)
	priority = models.IntegerField();
	deleted = models.CharField(max_length = 1)
	idUser = models.IntegerField();

	def __unicode__(self):
		return str(self.priority) + self.keyword

class LinkDB(models.Model):
	group = models.CharField(max_length = 50)
	priority = models.IntegerField()
	link = models.CharField(max_length = 50)
	description = models.CharField(max_length = 200)
	idUser = models.IntegerField()

	def __unicode__(self):
		return self.link

class ContentDB(models.Model):
	content = models.TextField()

	def __unicode__(self):
		return self.name

def save_content(id,content):
	try:
		try:
			c = ContentDB.objects.get(id = id)
		except ContentDB.DoesNotExist:
			c = ContentDB()
		c.content = content
		c.save()
		return c.id
	except ValueError:
		raise Http404

def save_keywords(id, keywords):
	prior = getLastPriorityK(id);
	for k in keywords:
		try:
			key = KeywordDB.objects.get(idUser=id, keyword=k.keyword)
		except KeywordDB.DoesNotExist:
			print prior
			prior = prior + 1
			key = KeywordDB(idUser=id,keyword=k.keyword,priority=prior,deleted='n')
			key.save()
def getLastPriorityK(id):
	try:
		keys = KeywordDB.objects.filter(idUser=id,deleted='n')
		prior = 0;
		for k in keys:
			if k.priority > prior:
				prior = k.priority
		return prior
	except ValueError:
		return 0

def save_links(id, links):
	try:
		oldL = LinkDB.objects.filter(idUser=id)
		for ol in oldL:
			ol.delete()
		for g in links:
			for l in g.link:
				e = LinkDB(idUser=id,link=l.url,description=l.description,priority=g.priority,group=g.group)
				e.save()
	except ValueError:
		raise Http404

def delete_keyword(id, keyword):
	try:
		dk = KeywordDB.objects.get(idUser=id,keyword=keyword)
		keys = KeywordDB.objects.filter(idUser=id,deleted='n')
		for k in keys:
			if dk.priority < k.priority:
				k.priority = k.priority - 1
				k.save()
		dk.deleted = 'y'
		dk.save()
	except ValueError:
		raise Http404

def create_keyword(id, keyword, priority):
	try:
		keys = KeywordDB.objects.filter(idUser=id,deleted='n')
		for k in keys:
			if priority <= k.priority:
				k.priority = k.priority + 1
				k.save()
		dk = KeywordDB(idUser=id,keyword=keyword,priority=priority,deleted='n')
		dk.save()
	except ValueError:
		raise Http404

def update_keyword(id, oldKey, newKey, priority):
	real_delete(id,oldKey)
	create_keyword(id, newKey, priority)

def real_delete(id,oldKey):
	try:
		dk = KeywordDB.objects.get(idUser=id,keyword=oldKey)
		keys = KeywordDB.objects.filter(idUser=id,deleted='n')
		for k in keys:
			if dk.priority < k.priority:
				k.priority = k.priority - 1
				k.save()
		dk.delete()
	except ValueError:
		raise Http404
